package com.wenzhoujie.http;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.Map.Entry;

import android.util.Log;

import com.wenzhoujie.app.App;

import com.wenzhoujie.common.HttpManager;
import com.wenzhoujie.constant.ApkConstant;

import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.RequestModel.RequestDataType;
import com.wenzhoujie.proxy.O2oSDAsyncHttpResponseHandlerProxy;
import com.wenzhoujie.proxy.O2oSDAsyncHttpResponseHandlerSimpleProxy;


import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.MiGBase64;

import com.ta.sunday.http.impl.SDAsyncHttpResponseHandler;
import com.ta.util.http.AsyncHttpClient;
import com.ta.util.http.RequestParams;
import com.ta.util.netstate.TANetWorkUtil;

/**
 * 接口请求类
 */
public class InterfaceServerold
{

	private static final String TAG = "InterfaceServer";

	private static final class Holder
	{
		static final InterfaceServerold mInterfaceServer = new InterfaceServerold();
	}

	private InterfaceServerold()
	{
	}

	public static InterfaceServerold getInstance()
	{
		return Holder.mInterfaceServer;
	}

	public void requestInterface(RequestModel model, SDAsyncHttpResponseHandler responseListener, boolean isNeedProxy)
	{
		requestInterface(model, true, responseListener, null, isNeedProxy);
	}

	public void requestInterface(RequestModel model, boolean isAsyncRequest, SDAsyncHttpResponseHandler responseListener, boolean isNeedProxy)
	{
		requestInterface(model, isAsyncRequest, responseListener, null, isNeedProxy);
	}

	public void requestInterface(RequestModel model, SDAsyncHttpResponseHandler responseListener, AsyncHttpClient httpClient, boolean isNeedProxy)
	{
		requestInterface(model, true, responseListener, httpClient, isNeedProxy);
	}

	public void requestInterface(RequestModel model, SDAsyncHttpResponseHandler responseListener, AsyncHttpClient httpClient)
	{
		requestInterface(model, true, responseListener, httpClient, true);
	}

	/**
	 * 请求接口方法
	 * 
	 * @param model
	 *            requestModel
	 * @param isAsyncRequest
	 *            是否异步请求
	 * @param responseListener
	 *            请求结果监听
	 * @param httpClient
	 *            AsyncHttpClient实例,如果该参数不为null则用该对象发起接口请求，否则用全局公用的一个对象发起请求
	 *            要产生AsyncHttpClient对象，调用HttpManager的静态方法产生。
	 */
	public void requestInterface(RequestModel model, boolean isAsyncRequest, SDAsyncHttpResponseHandler responseListener, AsyncHttpClient httpClient, boolean isNeedProxy)
	{

		if (TANetWorkUtil.isNetworkAvailable(App.getApplication()))
		{
			if (model != null)
			{
				RequestParams requestParams = getRequestParams(model);
				SDAsyncHttpResponseHandler listener = null;
				if (isNeedProxy)
				{
					listener = getDefaultProxy(responseListener, model);
				} else
				{
					listener = responseListener;
				}
				if (httpClient != null)
				{
					httpClient.post(ApkConstant.SERVER_API_URL, requestParams, listener);
				} else
				{
					if (isAsyncRequest)
					{
						HttpManager.getAsyncHttpClient().post(ApkConstant.SERVER_API_URL, requestParams, listener);
					} else
					{
						HttpManager.getSyncHttpClient().post(ApkConstant.SERVER_API_URL, requestParams, listener);
					}
				}
			}
		} else
		{
			SDToast.showToast("当前网络不可用!");
			responseListener.onFinishInMainThread(null);
		}
	}

	private SDAsyncHttpResponseHandler getDefaultProxy(SDAsyncHttpResponseHandler handler, RequestModel model)
	{
		return new O2oSDAsyncHttpResponseHandlerProxy(new O2oSDAsyncHttpResponseHandlerSimpleProxy(), handler);
	}

	private RequestParams getRequestParamsNoJson(RequestModel model)
	{
		RequestParams requestParams = new RequestParams();
		Object data = model.getmData();
		if (data != null)
		{
			Map<String, Object> mapData = (Map<String, Object>) data;
			printRequestUrl(model);
			for (Entry<String, Object> entry : mapData.entrySet())
			{
				String key = (entry.getKey()) == null ? "" : (entry.getKey());
				String value = (entry.getValue()) == null ? "" : (String.valueOf(entry.getValue()));
				// if (key.equals("pwd"))
				// {
				// value = MD5.hexdigest(value);
				// }
				requestParams.put(key, value);
			}
			requestParams.put("i_type", String.valueOf(model.getmRequestDataType()));
			requestParams.put("r_type", String.valueOf(model.getmResponseDataType()));
			// requestParams.put("soft_type", ApkConstant.SoftType.P2P);
			// requestParams.put("dev_type",
			// ApkConstant.DeviceType.DEVICE_ANDROID);
		}
		return requestParams;
	}

	private void printRequestUrl(RequestModel model)
	{
		String url = ApkConstant.SERVER_API_URL + "?";
		if (model != null && model.getmData() != null)
		{
			Map<String, Object> mapData = (Map<String, Object>) model.getmData();

			for (Entry<String, Object> entry : mapData.entrySet())
			{
				url = url + entry.getKey() + "=" + entry.getValue() + "&";
			}
			url = url + "i_type=" + String.valueOf(model.getmRequestDataType()) + "&" + "r_type=2";
		}
		Log.i(TAG, url);
	}

	private RequestParams getRequestParams(RequestModel model)
	{
		RequestParams requestParams = new RequestParams();
		 Map<String, Object> data = model.getmData();
		 Map<String, File> dataFile = model.getmDataFile();
		if (data != null)
		{
			String requestData = "";
			if (model.getmRequestDataType() == RequestDataType.BASE64)
			{
				requestData = MiGBase64.encode(JsonUtil.object2Json(data));
			} else if (model.getmRequestDataType() == RequestDataType.REQUEST)
			{
				requestData = JsonUtil.object2Json(data);
			}
			requestParams.put("requestData", requestData);
			requestParams.put("i_type", String.valueOf(model.getmRequestDataType()));
			requestParams.put("r_type", String.valueOf(model.getmResponseDataType()));
			requestParams.put("soft_type", ApkConstant.SoftType.O2O);
			requestParams.put("dev_type", ApkConstant.DeviceType.DEVICE_ANDROID);
		}
		if (dataFile != null)
		{
			for (Entry<String, File> itemFile : dataFile.entrySet())
			{
				if (itemFile != null)
				{
					try
					{
						requestParams.put(itemFile.getKey(), itemFile.getValue());
					} catch (FileNotFoundException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

		String urlString = ApkConstant.SERVER_API_URL + "?" + requestParams.toString();
		urlString = urlString.replace("r_type=1", "r_type=2");
		Log.i(TAG, urlString);
		return requestParams;
	}

}
